using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;

namespace deckAnalyser.Support
{
    class Downloader
    {
        private String from;
        private String to;

        public Downloader(String from, String to)
        {
            this.from = from;
            this.to = to;
        }

        public void download()
        {
            WebClient wc = new WebClient();
            byte[] data = null;
            try
            {
                data = wc.DownloadData(from);
            }
            catch(Exception)
            {
                return;
            }
            MemoryStream ms = new MemoryStream(data);

            FileStream fs = null;
            try
            {
                fs = File.OpenWrite(to);
                byte[] ba = ms.ToArray();
                fs.Write(ba, 0, ba.Length);
                fs.Close();
            }
            catch (Exception)
            {
                if (fs != null)
                    fs.Close();
            }
        }
    }

    public class ImageCache
    {
        private static String localPath;
        private static bool isOpen = false;
        public static bool IsOpen { get { return isOpen; } }

        public static void Open(string localPath)
        {
            if (isOpen) throw new Exception("Unable to open imagecache. Imagecache  is already open.");

            ImageCache.localPath = localPath;
            isOpen = true;
        }

        public static void Close()
        {
            if (!isOpen) throw new Exception("Unable to close imagecache. Imagecache is not open.");

            isOpen = false;
        }


        public static String Get(String key,String url)
        {
            if (File.Exists(localPath + key))
            {
                return localPath + key;
            }
            else
            {
                new Thread(new ThreadStart(new Downloader(url, localPath +"\\"+ key).download)).Start();

                return url;
            }
        }
    }
}
